package com.wechat.admin.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RestTemplateUtil {

    private static final RestTemplate restTemplate = createRestTemplate();

    public static RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    public static SimpleClientHttpRequestFactory factory = null;

    static {
        factory = new SimpleClientHttpRequestFactory();
        //读取超时5秒,默认无限限制,单位：毫秒
        factory.setReadTimeout(180000);
        //连接超时10秒，默认无限制，单位：毫秒
        factory.setConnectTimeout(60000);
    }

    public static <T> T post(String url, Map<String, Object> body, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        RestTemplate restTemplate = new RestTemplate(factory);

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(body), headers);
        try {
            log.info("发送请求");
            log.info("地址:" + url);
            T response = restTemplate.postForObject(url, entity, clazz);
            log.info("请求发送成功");
            return response;
        } catch (Exception e) {
            log.error("请求失败", e);
            throw e;
        }
    }


/*    public static JSONObject post(String url, HttpHeaders headers, Map<String, Object> body) {
        // 设置 RestTemplate 并添加消息转换器
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(body), headers);
        try {
            log.info("发送请求");
            log.info("地址:" + url);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
            log.info("请求发送成功");

            // 获取响应信息
            MediaType contentType = responseEntity.getHeaders().getContentType();
            String responseBody = responseEntity.getBody();

            // 根据 Content-Type 判断解析方式
            if (MediaType.APPLICATION_JSON.includes(contentType)) {
                return JSON.parseObject(responseBody);
            } else if (MediaType.TEXT_PLAIN.includes(contentType)) {
                return JSON.parseObject(responseBody);
            } else {
                throw new IllegalArgumentException("Unsupported content type: " + contentType);
            }
        } catch (HttpClientErrorException e) {
            log.error("HTTP 请求失败，状态码：" + e.getStatusCode(), e);
            // 尝试解析响应内容
            String responseBody = e.getResponseBodyAsString();
            try {
                return JSON.parseObject(responseBody);
            } catch (Exception ex) {
                log.error("解析响应体失败", ex);
                throw e;
            }
        } catch (Exception e) {
            log.error("请求失败", e);
            throw e;
        }
    }*/

    public static JSONObject postFor(String url, Map<String, Object> body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(body), headers);
        try {
            log.info("发送请求");
            log.info("地址: " + url);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();
                log.info("请求发送成功");
                log.info("响应: " + responseBody);
                return JSON.parseObject(responseBody);
            } else {
                log.error("请求失败，状态码: " + response.getStatusCodeValue());
                throw new RuntimeException("请求失败，状态码: " + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("请求失败", e);
            throw e;
        }
    }


    public static JSONObject postForTest(String url, HttpHeaders headers, Map<String, Object> body) {
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(body), headers);
        try {
            log.info("发送请求");
            log.info("地址:" + url);
            JSONObject response = restTemplate.postForObject(url, entity, JSONObject.class);
            log.info("请求发送成功");
            log.info("response信息为：{}", JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("请求失败", e);
            throw e;
        }
    }

    public static JSONObject post(String url, Map<String, Object> body) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        RestTemplate restTemplate = new RestTemplate(factory);

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(body), headers);
        try {
            log.info("发送请求");
            log.info("地址:" + url);
            JSONObject response = restTemplate.postForObject(url, entity, JSONObject.class);
            log.info("请求发送成功");
            return response;
        } catch (Exception e) {
            log.error("请求失败", e);
            throw e;
        }
    }

    public static class Header {
        HttpHeaders headers;

        public static Header builder() {
            Header heaader = new Header();
            heaader.headers = new HttpHeaders();
            return heaader;
        }

        public Header add(String key, String v) {
            headers.add(key, v);
            return this;
        }

        public HttpHeaders build() {
            return headers;
        }
    }

    public static class PostBody {
        Map<String, Object> body;

        public static PostBody builder() {
            PostBody postBody = new PostBody();
            postBody.body = new HashMap<>();
            return postBody;
        }

        public PostBody add(String s, Object o) {
            body.put(s, o);
            return this;
        }

        public Map<String, Object> build() {
            return body;
        }

        public PostBody addIfNotNull(String s, Object o) {
            if (o != null) {
                body.put(s, o);
            }
            return this;
        }
    }

    private static RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        fastJsonHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
        restTemplate.getMessageConverters().add(0, fastJsonHttpMessageConverter);

        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(StandardCharsets.UTF_8));

        return restTemplate;
    }

    public static JSONObject postForIcp(String url, Map<String, Object> body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(body), headers);
        try {
            log.info("发送请求");
            log.info("地址: " + url);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();
                log.info("请求发送成功");
                log.info("响应: " + responseBody);
                return JSON.parseObject(responseBody);
            } else {
                log.error("请求失败，状态码: " + response.getStatusCodeValue());
                throw new RuntimeException("请求失败，状态码: " + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("请求失败", e);
            throw e;
        }
    }
}
